import { HYDRATE } from "next-redux-wrapper";
import { ArticleTypes } from "redux/constants";

const initialState = {
  loading: false,
  data: null,
  error: null,
};

export const list = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    case ArticleTypes.GET_LIST_REQUEST:
      return { ...state, ...{ loading: true } };
    case ArticleTypes.GET_LIST_SUCCESS:
      return {
        loading: false,
        error: action.payload.message,
        data: action.payload.data,
      };

    // Object.assign({}, state, {
    //   loading: false,
    //   error: action.payload.message,
    //   data: action.payload.data,
    // });

    // {
    //   ...state,
    //   ...{
    //     loading: false,
    //     error: action.payload.message,
    //     data: action.payload.data,
    //   },
    // };
    case ArticleTypes.GET_LIST_FAILURE:
      return {
        ...state,
        ...{ loading: false, error: action.payload, data: null },
      };
    default:
      return state;
  }
};

export const publish = (state = initialState, action) => {
  switch (action.type) {
    case HYDRATE:
      return { ...state, ...action.payload };
    case ArticleTypes.PUBLISH_REQUEST:
      return { ...state, ...{ loading: true } };
    case ArticleTypes.PUBLISH_SUCCESS:
      return {
        ...state,
        ...{
          loading: false,
          error: action.payload.message,
          data: action.payload.data,
        },
      };
    case ArticleTypes.PUBLISH_FAILURE:
      return {
        ...state,
        ...{ loading: false, error: action.payload, data: null },
      };
    default:
      return state;
  }
};

const article = {
  list,
  publish,
};

export default article;
